//
//  NetHandler.m
//  UI_10.13_豆瓣
//
//  Created by 李荃荃 on 14-10-13.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NetHandler.h"


@implementation NetHandler

+ (void)networkWithURL:(NSString *)urlStr comaletion:(void(^)(id result)) block
{
    NSString * str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:str];
    
    //2 创建请求
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:60];
    request.HTTPMethod = @"GET";
    //3 连接服务器
    // 异步连接服务器
    // 参数1 请求
    // 参数2 操作队列 网络请求结束之后返回到哪个线程
    // 参数3 当网络请求结束之后， 会执行block中的代码
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]  completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //对 数据进行处理 刷新视图（reloadData）,给各种label赋值
        
        
        
        // 获取caches文件夹, 用来保存缓存数据
        NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        // 文件名的选择有两种: 1. 借口的地址当作文件名
        // 2.利用NSObject的哈希值
        
        NSInteger hash = [urlStr hash];
        
        NSString *filePath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%da.aaa", hash]];

        if (data != nil) {
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:&error];
            

            BOOL re = [NSKeyedArchiver archiveRootObject:data toFile:filePath];
            NSLog(@"%d",re);
            block(result);
        } else {
            NSLog(@"网络请求失败");
            //在这里读取之前存储的数据
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"网络连接失败，请检查您的网络！！" delegate:self cancelButtonTitle:@"Cancle" otherButtonTitles:@"OK", nil];
            
            [alertView show];
            [alertView release];
            
            NSData *dataRead = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            NSError *errer = nil;
            id result = [NSJSONSerialization JSONObjectWithData:dataRead options:NSJSONReadingMutableContainers error:&errer];

            block(result);
        }
    }];

}


@end
